package edu.hawaii.myisern.action;


import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationError;

/**
 * Handles the login authentication of the MyIsern System.
 * 
 * @author Sonwright M. Gomez
 * @author Ivan Wu
 * @author Phillip Le
 *
 */
public class IndexActionBean extends MyIsernActionBean {

  @Validate(required = true)
  private String username;
  /** The password for the user. */
  @Validate(required = true)
  private String password;
  /** An error string, always displayed, but invisible if empty. */
  private String errorMessage = "";
  
  /**
   * Returns the error message, which may be empty.
   * Indicates if someone tried to pop an empty stack. 
   * @return The error message. 
   */
  public String getErrorMessage() {
    return this.errorMessage;
  }
  
  /**
   * Set's the error message for the user.
   * 
   * @param errorMessage containing error Message. 
   */
  public void setErrorMessage(String errorMessage) {
    this.errorMessage = errorMessage;
  }
  
  /**
   * Set's the username.
   * 
   * @param username The user's name.
   */
  public void setUsername(String username) {
    this.username = username;
  }

  /**
   * Get's the username.
   * 
   * @return username The user's name.
   */
  public String getUsername() {
    return username;
  }
  
  /**
   * Set's the password.
   * 
   * @param password The user's password.
   */
  public void setPassword(String password) {
    this.password = password;
  }

  /**
   * Get's the password.
   * 
   * @return password The user's password.
   */
  public String getPassword() {
    return password;
  }
  
  /**
   * A handler that performs the action when the 'login' button is pressed.
   * 
   * @return A Resolution indicating to redisplay the mainmenu.jsp page
   * if the user entered correct username and password or a Resolution
   * indicated to redisplay the login page with error message if wrong
   * username and/or password has been entered. 
   */
  public Resolution login() {
   if (getUsername().equalsIgnoreCase("admin")) {
     if (getPassword().equals("password")) {
       (getContext().getRequest()).getSession().setAttribute("user", username); 
       return new ForwardResolution("/mainMenu.jsp");
     }
     else {
       ValidationError error = new SimpleError("Wrong Password");
       getContext().getValidationErrors().add("password", error);
       return getContext().getSourcePageResolution();
     }
   }
   else {
     ValidationError error = new SimpleError("Wrong Username");
     getContext().getValidationErrors().add("username", error);
     return getContext().getSourcePageResolution();
   }
  }
  
}
